package com.pj.wisdomlogistics.api;

import android.os.Environment;

import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.pj.wisdomlogistics.BuildConfig;
import com.pj.wisdomlogistics.MyApplication;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2016/10/14.
 */
public class ApiWrapper {

    private static final String HTTP_CACHE_DIR = "http";
    public static final int HTTP_CACHE_SIZE = 20 * 1024 * 1024;
    public static final int HTTP_CONNECT_TIMEOUT = 120 * 1000;
    public static final int HTTP_READ_TIMEOUT = 120 * 1000;

    private static Retrofit mRetrofit;
    private static ApiService mApiService;

    public static Retrofit getRetrofit() {
        if (mRetrofit == null) {
            if (mRetrofit == null) {

                OkHttpClient mClient = new OkHttpClient.Builder()
                        .addInterceptor(new LoggerInterceptor("TAG"))
                        .addNetworkInterceptor(new StethoInterceptor())
                        .cache(new Cache(getHttpCacheDir(),HTTP_CACHE_SIZE))
                        .connectTimeout(HTTP_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                        .readTimeout(HTTP_READ_TIMEOUT,TimeUnit.MILLISECONDS)
                        .addInterceptor(new CacheInterceptor())
                        .build();

                mRetrofit = new Retrofit.Builder()
                        .client(mClient)
                        .baseUrl(BuildConfig.SERVER_HOST)
                        .addConverterFactory(GsonConverterFactory.create())
                        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                        .build();
            }
        }
        return mRetrofit;
    }

    public static ApiService getApiService(){
        if(mApiService == null){
            mApiService = getRetrofit().create(ApiService.class);
        }
        return mApiService;
    }


    public static final File getHttpCacheDir() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return new File(MyApplication.getApplication().getExternalCacheDir(), HTTP_CACHE_DIR);
        }
        return new File(MyApplication.getApplication().getCacheDir(), HTTP_CACHE_DIR);
    }
}
